using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlServerCe;

namespace CEQuery
{
    public partial class OpenDB : Form
    {
        public OpenDB()
        {
            InitializeComponent();
        }

        public OpenDB(string startupFile)
        {
            InitializeComponent();

            if (System.IO.File.Exists(startupFile))
            {
                CEFile = startupFile;
                txtFile.Text = startupFile;
                txtPassword.Focus();
            }
        }

        public string CEFile { get; private set; }
        public string ConnectionString { get; private set; }
        private bool ValidateInput()
        {
            bool isValid = true;
            if (this.txtFile.Text.Trim() == string.Empty)
            {
                isValid = false;
                errValidation.SetError(btnSelect, "Select a file.");
            }
            else
            {
                errValidation.SetError(btnSelect, string.Empty);
            }
            return isValid;
        }
        private void btnSelect_Click(object sender, EventArgs e)
        {
            openFileDialogue.Title = "Open the SQL CE File";
            openFileDialogue.Filter = "SQL CE Files (*.sdf)|*.sdf";
            openFileDialogue.RestoreDirectory = true;
            if (openFileDialogue.ShowDialog() == DialogResult.OK)
            {
               txtFile.Text = openFileDialogue.FileName;
               txtPassword.Focus();
            }
        }

        private void OpenDB_Load(object sender, EventArgs e)
        {

        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            if (!ValidateInput())
            {
                return;
            }
            //ConnectionString = string.Format("Data Source={0};Password={1};Max Database Size=4091;Max Buffer Size = 1024;Default Lock Escalation =100;Encrypt Database=TRUE", txtFile.Text, txtPassword.Text);
            CEFile = txtFile.Text;
            ConnectionString = string.Format("Data Source={0};Password={1};Max Database Size=4091;Max Buffer Size = 1024;Default Lock Escalation =100;Encrypt Database={2}", txtFile.Text, txtPassword.Text, txtPassword.Text.Length == 0 ? "FALSE" : "TRUE");
            using (SqlCeConnection connection = new SqlCeConnection(ConnectionString))
            {
                try
                {
                    connection.Open();
                    btnHiddenOK.PerformClick();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }                
            }
        }

    }
}